//
//  ServiceViewController.m
//  ZhiHuiLiJiang
//
//  Created by Work on 2018/11/12.
//  Copyright © 2018年 王雅鹏. All rights reserved.
//服务VC

#import "ServiceViewController.h"
#import "GuideSearchView.h"//搜索框View
#import "LLSearchViewController.h"//搜索VC
#import "BYServiceTableViewCell.h"//服务标题tableViewCell
#import "OneCollectionViewCell.h"//服务瀑布流cell
#import "BYserverModel.h"//服务数据源Model
#import "BYserverMuneModel.h"//服务标题model

static NSString *tableViewCellIentifier = @"serviceTableViewCellID";//左侧标题tableViewCellId
static NSString *headerViewIdentifier = @"collectionHederViewID";//瀑布流头部ID
static NSString *collectionViewCellIdentifier = @"rightItemcellID";//瀑布流cellID
@interface ServiceViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,GuideSearchViewDelegate,UIScrollViewDelegate>{
    NSInteger _selectIndex;//选中的标题数组下标
    BOOL _isScrollDown;//记录瀑布流滚动的方向
}
/**搜索框*/
@property (nonatomic ,strong) GuideSearchView * searchView;
/**左侧标题模块tableView*/
@property (nonatomic ,strong) UITableView * maintableView;
/**右侧瀑布流View*/
@property (nonatomic ,strong) UICollectionView * collectionView;
/**瀑布流头部View*/
@property (nonatomic,strong) UIView *headerView;
/**左侧标题数组*/
@property (nonatomic ,strong) NSMutableArray * titledataArray;
/**右侧item数组*/
@property (nonatomic ,strong) NSMutableArray * dataArray;
/**数据源数组*/
@property (nonatomic ,strong) NSMutableArray * modelArray;

@end
@implementation ServiceViewController
#pragma mark- init初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addInitSubView];
    [self getmenuData];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
    if (self.tabBarController.tabBar.isHidden) {
        self.tabBarController.tabBar.hidden = NO;
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
}
- (void)addInitSubView{
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化数据数组
    self.dataArray = [[NSMutableArray alloc]init];
    self.titledataArray = [[NSMutableArray alloc]init];
    self.modelArray = [[NSMutableArray alloc]init];
    
    //右侧瀑布流View
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    layout.itemSize = CGSizeMake(70, 40);
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(90, BY_Nav_H+BY_Height(20), SCREENWIDTH-90, KSCREEHEGIHT - BY_NavBot_H - BY_Height(20)-49) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[OneCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellIdentifier];
    layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, 20);
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];
    [self.view addSubview:_collectionView];
    //左侧标题模块tableView
    _maintableView = [[UITableView alloc]initWithFrame:CGRectMake(0, BY_Nav_H+BY_Height(20), 90,KSCREEHEGIHT - BY_NavBot_H - BY_Height(20))style:UITableViewStylePlain];
    _maintableView.dataSource = self;
    _maintableView.delegate = self;
    _maintableView.rowHeight = 50;
    _maintableView.tableFooterView = [[UIView alloc]init];
    _maintableView.backgroundColor = RGBA(246, 246, 246, 1);
    _maintableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_maintableView registerClass:[BYServiceTableViewCell class] forCellReuseIdentifier:tableViewCellIentifier];
    [self.view addSubview:_maintableView];
    [self.view addSubview:self.searchView];
}
- (GuideSearchView *)searchView{//搜索框
    if (!_searchView) {
        _searchView = [[GuideSearchView alloc]initWithFrame:CGRectMake(0, 0, KSCREEWIDTH, BY_Nav_H) with:@""];
        _searchView.delegate = self;
        _searchView.backgroundColor = [UIColor whiteColor];
    }
    return _searchView;
}

#pragma mark- 左侧tableView的代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titledataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BYserverMuneModel *model = self.modelArray[indexPath.row];
    BYServiceTableViewCell *cell = [[BYServiceTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableViewCellIentifier];
    [cell setModel:model];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _selectIndex = (int)indexPath.row;
    NSIndexPath* cellIndexPath = [NSIndexPath indexPathForItem:0 inSection:_selectIndex];
    UICollectionViewLayoutAttributes* attr = [self.collectionView.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:cellIndexPath];
    UIEdgeInsets insets = self.collectionView.scrollIndicatorInsets;
    CGRect rect = attr.frame;
    rect.size = self.collectionView.frame.size;
    rect.size.height -= insets.top + insets.bottom;
    CGFloat offset = (rect.origin.y + rect.size.height) - self.collectionView.contentSize.height;
    if ( offset > 0.0 ) rect = CGRectOffset(rect, 0, -offset);
    [self.collectionView scrollRectToVisible:rect animated:YES];
}
- (void)selectMainTableViewRowAtIndexPath:(NSInteger)index{// 当拖动CollectionView的时候，处理TableView
    [self.maintableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}

#pragma mark- 右侧瀑布流的代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_dataArray[section]count];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return _dataArray.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellWidth = (SCREENWIDTH - 90 -30) / 3.0;
    CGFloat cellHeight = 60;
    return CGSizeMake(cellWidth, cellHeight);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(20, 0, 10, 0);//分别为上、左、下、右
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 20;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    OneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCellIdentifier forIndexPath:indexPath];
    [cell setBYserverModel:self.dataArray[indexPath.section][indexPath.row]];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    //如果是头视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
        //添加头视图的内容
        [self addCollectionHeadViewContent:[NSString stringWithFormat:@"%@",self.titledataArray[indexPath.section]]];
        //头视图添加view
        [header addSubview:self.headerView];
        return header;
    }
    return nil;
}
- (void)addCollectionHeadViewContent:(NSString *)str{//设置头部内容
    UILabel *header=[[UILabel alloc]init];
    header.frame=CGRectMake(8, 0, self.view.frame.size.width, 20);
    header.backgroundColor = [UIColor whiteColor];
    header.textAlignment = NSTextAlignmentLeft;
    header.text = str;
    header.textColor = RGBA(152, 152, 152, 1);
    header.font = H12;
    self.headerView=header;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
    // 当前CollectionView滚动的方向向上，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (!_isScrollDown && collectionView.dragging){
        [self selectMainTableViewRowAtIndexPath:indexPath.section];
    }
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(nonnull UICollectionReusableView *)view forElementOfKind:(nonnull NSString *)elementKind atIndexPath:(nonnull NSIndexPath *)indexPath{// CollectionView分区标题展示结束
    if (_isScrollDown && collectionView.dragging){
        [self selectMainTableViewRowAtIndexPath:indexPath.section + 1];
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BYserverModel *model =self.dataArray[indexPath.section][indexPath.row];
    //统计埋点
    NSDictionary *dic = @{@"uuid":[SaveCacheData loadDataStrWithKey:currentUserudid]==NULL?@"none":[SaveCacheData loadDataStrWithKey:currentUserudid],@"time":@([[self getNowTimeTimestamp] integerValue]),@"mid":model.mid,@"type":@([self menuStatisticsType:model.type])};
    [self requestClickMenuStatisticsParams:dic];
    
    if(model.type == 3){//小程序
        BOOL isWX = [WXApi isWXAppInstalled];//是否安装微信（YES已安装、NO未安装)
        if (isWX) {
            NSDictionary *dict = [self dictionaryWithJsonString:[model.url stringByReplacingOccurrencesOfString:@"\n" withString:@""]];
            WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
            launchMiniProgramReq.userName = dict[@"userName"];  //拉起的小程序的username
            launchMiniProgramReq.path =  dict[@"path"];;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
            launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
            [WXApi sendReq:launchMiniProgramReq];
        }else{
            NSString *xcxUrl = @"";
            if ([model.mid isEqualToString:@"jinpaijieshuo"]) {//金牌解说
                xcxUrl = noWeChatJieShuo;
            }else if ([model.mid isEqualToString:@"yunFoodBooking"]){//智慧食堂
                xcxUrl = noWeChatShiTang;
            }else{
            }
            BYWebVC *webVC = [[BYWebVC alloc]init];
            webVC.url = xcxUrl;
            webVC.titleStr = model.name;
            [self.navigationController pushViewController:webVC animated:YES];
        }
    }else{
        BYWebVC *webVC = [[BYWebVC alloc]init];
        webVC.url = model.url;//@"https://m.kuaidi100.com/app/?coname=cmb&hdisplay=web";
        webVC.titleStr = model.name;// @"我的快递";
        [self.navigationController pushViewController:webVC animated:YES];
        
    }
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {if (jsonString == nil) {return nil;}NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];NSError *err;NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];if(err) {NSLog(@"json解析失败：%@",err);return nil;}return dic;}

#pragma mark - UIScrollView代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{// 标记一下CollectionView的滚动方向，是向上还是向下
    static float lastOffsetY = 0;
    if (self.collectionView == scrollView){
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

#pragma mark- 数据处理
- (NSString *)getNowTimeTimestamp{//统计的时间处理
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    return timeSp;
}
- (NSInteger)menuStatisticsType:(NSInteger)type{//统计的type处理
    if (type ==0 ||type ==2 ) {
        return 1;
    }else{
        return 2;
    }
}

#pragma mark- 用户交互
-(void)screachClick{//点击了搜索按钮
    LLSearchViewController *VC = [[LLSearchViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark- 网络请求
- (void)getmenuData{//获取服务页面的数据
    BY_kWeakSelf(ws);
    NSDictionary *dict;
    [BYNetworking requestGetOrPostWithType:GET url:LJURL_menu_group params:dict success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
        NSDictionary *dataArr = [data objectForKey:@"data"];
        for (NSDictionary *dict in dataArr) {
            BYserverMuneModel *model= [BYserverMuneModel mj_objectWithKeyValues:dict];
            [ws.titledataArray addObject:model.decrp];
            [ws.dataArray addObject:model.sublist];
            [ws.modelArray addObject:model];
        }
        [ws.maintableView reloadData];
        [ws.collectionView reloadData];
        [ws.maintableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    } fail:^(NSError * _Nonnull error) {
    } showHUD:YES];
}
- (void)requestClickMenuStatisticsParams:(NSDictionary *)dict{//点击菜单的统计
    [BYNetworking requestGetOrPostWithType:POST url:LJURL_open_mune params:dict success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
    } fail:^(NSError * _Nonnull error) {
    } showHUD:NO];
}


@end
